<?php

namespace Hilaoyu\LaravelExtend\Services\Variables;
use Hilaoyu\LaravelExtend\ControllerBaseResource;
use Illuminate\Http\Request;


abstract class VariablesControllerAbstract extends ControllerBaseResource
{
    public function saveMult(Request $request){
        $variables = $request->input('variables',[]);

        $variables = (array)$variables;
        $entity = $this->entity();

        foreach ($variables as $variable){
            if(!is_array($variable)){
                continue;
            }
            if(!$entity->save($variable,data_get($variable,'id'))){
                comResponse()->failed('保存失败')->withErrors($entity->getError());
                break;
            }
        }

        return $this->renderingResponse();
    }


    protected function alterModelsQuery($query, Request $request)
    {
        $query = parent::alterModelsQuery($query, $request);

        $search = [
            'keyword' => $request->get('keyword', ''),
        ];
        $keys = $request->route('_keys', []);
        if(is_array($keys) && !empty($keys)){
            $query = $query->whereIn('key', $keys);
        }
        if(!empty($search['keyword'])){
            $query = $query->where(function ($q) use ($search){
                return $q->orWhere('key','like',$search['keyword'])
                    ->orWhere('name','like',$search['keyword'])
                    ->orWhere('remark','like',$search['keyword'])
                    ;
            });
        }


        $formSearch = [
            'keyword' => [
                'value' => $search['keyword'],
                'label' => '键/名称',
                'type' => 'text',
            ] ,
        ];

        comResponse()->with($formSearch,'form_search');
        return $query;
    }

    protected function alterModelSaveData(Request $request, $id = '')
    {
        $data = [
            'name' => $request->input('name',''),
            'key' => $request->input('key',''),
            'value' => $request->input('value',''),
            'type' => $request->input('type',''),
            'remark' => $request->input('remark',''),
        ];
        return $data;
    }
}
